package com.java.netty.common.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;


public class PptpDecoder extends ByteToMessageDecoder {
    private String ip;

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        if (ip == null) {
            ip = ctx.channel().remoteAddress().toString();
        }
        // 判断当前可读为大于等于6
        if (in.isReadable(Packet.PACKET_MIN_LEN)) {
            int dataLen = Packet.byte2Int(in.getByte(4), in.getByte(5));
            if (!in.isReadable((dataLen + Packet.PACKET_MIN_LEN))) {
                return;
            }
            Packet packet = Packet.decodePacket(new Packet(), in);
            if (packet != null) {
                out.add(packet);
            } else {
                // 说明packet.data长度大于最大限制，将连接关闭。
                ctx.close();
            }
        }
    }
}
